function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json) {
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' +
                      json.tmpo_poc_name + '</a> ' +
                      'Phone: (' + json.tmpo_poc_phone.substr(0,3) + ') ' +
                      json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").html(val);       
        }
    ); 
}

function getEmails() {
    $.ajax({
        url: '/api/tmpo/options/email/',
        type: "GET",
        async: false,
        dataType: "json",
        success: function(json){ 
            json_data = json.emails;
        },
        complete: function(){            
        },
        error: function(){}
    });
}

function postEmail(section, email_keyword) {
    var form_email_data = {
        subject: $("#proto"+section_obj[section]+
        "HTML input[name='tmpo_"+section_obj[section_obj[section]]+
        "_subject_line']").val(),
        markup: $("#proto"+section_obj[section]+
        "HTML textarea[name='tmpo_"+section_obj[section_obj[section]]+
        "_text']").val(),
        keyword: email_keyword
    };
    $.ajax({
        url: '/api/tmpo/options/email/',
        type: "POST",
        data: form_email_data,
        async: false,
        dataType: "json",
        success: function(){},
        complete: function(){
            showSection(section);
        },
        error: function(){}
    });
}

var json_data = [];

var section_obj = {
    'New Request Notification':'request_notify',
    'Request Approved':'request_approved',
    'Request Disapproved':'request_disapproved',
    'request_notify':'NewreqNotify',
    'request_approved':'ReqApproved',
    'request_disapproved':'ReqDisapproved',
    'NewreqNotify':'newreq_notify',
    'ReqApproved':'req_approved',
    'ReqDisapproved':'req_disapproved'
};

var email_type_obj = {
    'request_notify':'tmpo_appt_rem',
    'request_approved':'tmpo_appt_conf',
    'request_disapproved':'tmpo_not_canc'
};

var validateForm = function(section) {
    var error_count = 0;
    hideMessages(section_obj[section]);
    $("#proto"+section_obj[section]+"HTML "+
        "span[class='fieldData tableErrorColor']").removeClass("tableErrorColor");
    $("#proto"+section_obj[section]+"HTML "+
        "span[class='errorMessage']").remove();
    $("#proto"+section_obj[section]+"HTML "+
        "input[class='formError']").removeClass('formError');
    var req_fields = [
        "proto"+section_obj[section]+
        "HTML input[name='tmpo_"+section_obj[section_obj[section]]+
        "_subject_line']",
        "proto"+section_obj[section]+
        "HTML textarea[name='tmpo_"+section_obj[section_obj[section]]+
        "_text']"
    ];
    $.map( req_fields, function(field) {
        if( !$("#"+field).val()) {
            error_count++;
            $("#"+field).parent().append('<span class="errorMessage">'+
                'Please complete required field.</span>');
            $("#"+field).parent().addClass("tableErrorColor");
            $("#"+field).addClass("formError");
        }
    });
    if(error_count){
        $("#proto"+section_obj[section]+"HTML "+
            "p:eq(3) span[class='generalErrorMessage']").show();
            return false;
    }else {
        $("#proto"+section_obj[section]+"HTML "+
            "p:eq(3) span[class='waitMessage']").show();
            return true;
    }
};

var editSection = function(section) {
    getEmails();
    hideSection(section);   
    $("#button_edit_"+section_obj[section_obj[section]]).after($("#protoEdit"+
        section_obj[section]+"HTML").html());
    $("#button_cancel_"+section_obj[section_obj[section]]).bind("click", 
    function() {
        showSection(section);
        return false;
    });    
    var grep_email_data = jQuery.grep(json_data, function(n,i) {
            return (n['keyword'] == email_type_obj[section]);
    });
    $("#proto"+section_obj[section]+
        "HTML input[name='tmpo_"+section_obj[section_obj[section]]+
        "_subject_line']").val(grep_email_data[0].subject);
    $("#proto"+section_obj[section]+
        "HTML textarea[name='tmpo_"+section_obj[section_obj[section]]+
        "_text']").val(grep_email_data[0].markup);
    $("#button_save_"+section_obj[section_obj[section]]).bind("click", 
        function(){
            if (validateForm(section)) {
                postEmail(section, grep_email_data[0].keyword);
                return false;
            }
            return false;
    });
};

var showSection = function(section) {  
    getEmails();
    hideSection(section);        
    $("#button_edit_"+section_obj[section_obj[section]]).after($("#protoShow"+
        section_obj[section]+"HTML").html());
    $("#button_edit_"+section_obj[section_obj[section]]).bind("click", 
    function() {
        editSection(section);
        return false;
    });    
    var grep_email_data = jQuery.grep(json_data, function(n,i) {
            return (n['keyword'] == email_type_obj[section]);
    });
    $("#proto"+section_obj[section]+
        "HTML p:eq(0) span[class='fieldData']").html(
            grep_email_data[0].subject
    );
    $("#proto"+section_obj[section]+
        "HTML p:eq(1) span[class='fieldData']").html(
            grep_email_data[0].markup
    );
};

var hideSection = function(section) {
    $("#proto"+section_obj[section]+"HTML p").remove();
};

var hideMessages = function(section) {
    if (section){
        $("#proto"+section+"HTML "+
            "span[class='waitMessage']").hide();
        $("#proto"+section+"HTML "+
            "span[class='generalErrorMessage']").hide();    
    }else{
        $("span[class='waitMessage']").hide();
        $("span[class='generalErrorMessage']").hide();
    }
};

var toggleSection = function(){
    $("td a[class='headerToggle']").toggle(
    function() {
        var this_element = this;
        $("#"+section_obj[$(this).text()]+
            " td[class='tableHeadColor']").addClass('tableActiveColor');
        $("#"+section_obj[$(this).text()]+ " a[class='headerToggle'] "+
        "img").attr({src:'/images/icons/collapse.gif'});
        
        $("#"+section_obj[$(this).text()]+" tr").show();
        $("#"+section_obj[$(this).text()]+
            " tr:last td").attr({style:'position: static;'});
        $("#proto"+section_obj[section_obj[$(this).text()]]+
            "HTML").show(function(){
                showSection(section_obj[$(this_element).text()]);                
        });
    },
    function() { 
        var this_element = this;
        $("#"+section_obj[$(this).text()]+
            " td").removeClass('tableActiveColor');
        $("#"+section_obj[$(this).text()]+ " a[class='headerToggle'] "+
        "img").attr({src:'/images/icons/expand.gif'});
        $("#"+section_obj[$(this).text()]+" tr:last").slideUp();
        $("#"+section_obj[$(this).text()]+" tr:last td").slideUp();
        $("#"+section_obj[$(this).text()]+" tr:last td").attr({style:''});
        $("#proto"+section_obj[section_obj[$(this).text()]]+
            "HTML").hide(function(){
                hideSection(section_obj[$(this_element).text()]);                
        });
    });
};

$(function() {
    Functional.install();
    getSiteCfg();
    hideMessages();
    toggleSection();
});
